<template>
  <div class="grid_gadget_tempalte">
    <Portal to="right-disable"
            v-loading="loading"
            :disabled="!queryModelDefaultSetting.showSetting">
      <DashboardInterceptConsumer :gadgetId="id"
                                  shadow="never"
                                  class="aui-card--fill"
                                  :style="{ height: !isHasData ? gadgetHeight-20 + 'px' : ''}">

        <el-card shadow="never"
                 class="aui-card--fill">
          <div>
            <div class="control-section"
                 style="margin: 10px 10px;">
              <div class="content-wrapper"
                   :style="{ height: !isHasData ? gadgetHeight-20 + 'px' : ''}">
                <div style="height:50px;display:flex;align-items:center;position:relative">
                  <el-popover ref="filterPopover"
                              @show="showFilterForm"
                              width="300"
                              placement="bottom-start"
                              trigger="click">
                    <el-form ref="form"
                             :model="filterform"
                             label-position="top">
                      <el-form-item :label="$t('custom.component.gadget.status')">
                        <el-select v-model="filterform.status"
                                   multiple
                                   size="small"
                                   clearable
                                   filterable
                                   :placeholder="$t('custom.component.gadget.select')"
                                   style="width:100%">
                          <el-option v-for="item in statusOptions"
                                     :key="item.value"
                                     :label="item.label"
                                     :value="item.value">
                            <span>{{item.label}}</span><span v-if="filterform.status == item.value"
                                  style="float:right;padding-top:12px"></span>
                          </el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item :label="$t('custom.component.gadget.priority')">
                        <el-select v-model="filterform.priority"
                                   clearable
                                   filterable
                                   size="small"
                                   multiple
                                   :placeholder="$t('custom.component.gadget.select')"
                                   style="width:100%">
                          <el-option value="1"
                                     label="Instant">
                            <el-badge is-dot
                                      class="item"
                                      style="padding:8px 5px 0 0"
                                      type="danger"></el-badge><span>Instant</span>
                          </el-option>
                          <el-option value="2"
                                     label="Urgent">
                            <el-badge is-dot
                                      class="item"
                                      style="padding:8px 5px 0 0"
                                      type="warning"></el-badge><span>Urgent</span>
                          </el-option>
                          <el-option value="3"
                                     label="Normal">
                            <el-badge is-dot
                                      class="item"
                                      style="padding:8px 5px 0 0"
                                      type="success"></el-badge><span>Normal</span>
                          </el-option>
                          <el-option value="4"
                                     label="Low">
                            <el-badge is-dot
                                      class="item"
                                      style="padding:8px 5px 0 0"
                                      type="info"></el-badge><span>Low</span>
                          </el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item :label="$t('custom.component.gadget.type')">
                        <el-select v-model="filterform.type"
                                   clearable
                                   filterable
                                   size="small"
                                   multiple
                                   :placeholder="$t('custom.component.gadget.select')"
                                   style="width:100%">
                          <el-option value="1"
                                     label="Incomplete Settings">
                            <img :src="$ossLink+'/app/mspbots_theme_icon/incomplete_settings.png'"
                                 style="width:20px"><span style="margin-left:10px">Incomplete Settings</span>
                          </el-option>
                          <el-option value="2"
                                     label="Integration Status">
                            <img :src="$ossLink+'/app/mspbots_theme_icon/integrations.png'"
                                 style="width:20px"><span style="margin-left:10px">Integration Status</span>
                          </el-option>
                          <el-option value="3"
                                     label="Notification">
                            <img :src="$ossLink+'/app/mspbots_theme_icon/notification.png'"
                                 style="width:20px"><span style="margin-left:10px">Notification</span>
                          </el-option>'
                          <el-option value="4"
                                     label="User Message Disable">
                            <img :src="$ossLink+'/app/mspbots_theme_icon/teams_command.png'"
                                 style="width:20px"><span style="margin-left:10px">User Message Disable</span>
                          </el-option>
                          <el-option value="5"
                                     label="Sync And Authorizati">
                            <img :src="$ossLink+'/app/mspbots_theme_icon/sync.png'"
                                 style="width:20px"><span style="margin-left:10px">Sync And Authorizati</span>
                          </el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item :label="$t('custom.component.gadget.assignee')">
                        <el-select v-model="filterform.assignee"
                                   clearable
                                   filterable
                                   size="small"
                                   multiple
                                   :placeholder="$t('custom.component.gadget.select')"
                                   style="width:100%">
                          <el-option v-for="item in assigneeOptions"
                                     :key="item.id"
                                     :label="item.realName"
                                     :value="item.assignee">
                            <span style="display:inline-block;width:28px;height:28px;border-radius:50%;background-color:#1890FF;text-align:center;line-height:28px;color:#fff;margin-right:10px">{{item.realName | assigneeFilter}}</span><span>{{item.realName}}</span>
                          </el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="Date">
                        <el-cascader ref="dateCascader"
                                     style="width:100%"
                                     clearable
                                     filterable
                                     :props="{ expandTrigger: 'hover',emitPath:false }"
                                     v-model="filterform.createTime"
                                     @change="cascaderChange"
                                     :options="dateOptions">
                          <template slot-scope="{  data }">
                            <span>{{ data.label }}</span>
                          </template>
                        </el-cascader>
                      </el-form-item>
                      <div v-if="filterform.createTime === 'Custom DateRange'">
                        <el-date-picker style="width:100%"
                                        v-model="filterform.dateRange"
                                        type="daterange">
                        </el-date-picker>
                      </div>
                      <el-form-item style="float:right;margin-bottom:0">
                        <span @click="filterformReset"
                              class="cuifont icon_arrow_sync filterformReset"
                              style="color:#17B3A3;margin-right:10px;font-size:14px;"> Reset</span>
                        <el-button @click="filterformApply(filterform)"
                                   type="primary"
                                   size="mini">Apply</el-button>
                      </el-form-item>
                    </el-form>
                    <el-button size="mini"
                               slot="reference"
                               type="primary"
                               style="margin-right:10px"
                               @click="filterVisible = !filterVisible">Filter</el-button>
                  </el-popover>
                  <el-dropdown trigger="click"
                               placement="bottom-start"
                               @command="sortCommand">
                    <el-button type="primary"
                               size="mini">
                      Sort
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu style="width:300px">
                        <el-dropdown-item v-for="(item,index) in sortOptions"
                                          :key="index"
                                          :command="item.value"
                                          :class="{'selected':sortStatus==item.value}">{{ item.label}}<span v-show="sortStatus==item.value"
                                class="el-icon-check"
                                style="float:right;padding-top:12px"></span></el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                  <el-input :placeholder="$t('custom.component.gadget.search')"
                            style="width:200px;position: absolute;right:5px"
                            clearable
                            prefix-icon="el-icon-search"
                            @input="inputFilter"
                            v-model="keyWords">
                  </el-input>
                </div>
                <div v-if="isHasData">
                  <el-table :data="comDataList"
                            :style="{ height: gadgetHeight-60 + 'px' }"
                            :height="gadgetHeight - 100 - maxColItem * 36"
                            style="color:#212529;overflow:scroll"
                            :row-style="rowStyle"
                            @cell-mouse-leave="showClickIcon=false"
                            @cell-mouse-enter="ncrFormat"
                            :show-overflow-tooltip='true'
                            :header-cell-style="{color:'#212529'}">
                    <el-table-column width="35"
                                     align="right">
                      <template slot-scope="scope">
                        <el-badge is-dot
                                  class="item"
                                  style="margin-top:6px"
                                  type="danger"
                                  v-if="scope.row.priority === 1"></el-badge>
                        <el-badge is-dot
                                  class="item"
                                  style="margin-top:6px"
                                  type="warning"
                                  v-if="scope.row.priority === 2"></el-badge>
                        <el-badge is-dot
                                  class="item"
                                  style="margin-top:6px"
                                  type="success"
                                  v-if="scope.row.priority === 3"></el-badge>
                        <el-badge is-dot
                                  class="item"
                                  style="margin-top:6px"
                                  type="info"
                                  v-if="scope.row.priority === 4"></el-badge>
                      </template>
                    </el-table-column>
                    <el-table-column label="Type"
                                     width="55"
                                     align="center">
                      <template slot-scope="scope">
                        <img src="https://oss.mspbots.ai/app/mspbots_theme_icon/incomplete_settings.png"
                             style="width:20px"
                             v-if="scope.row.type === 1">
                        <img src="https://oss.mspbots.ai/app/mspbots_theme_icon/integrations.png"
                             style="width:20px"
                             v-if="scope.row.type === 2">
                        <img src="https://oss.mspbots.ai/app/mspbots_theme_icon/notification.png"
                             style="width:20px"
                             v-if="scope.row.type === 3">
                        <img src="https://oss.mspbots.ai/app/mspbots_theme_icon/teams_command.png"
                             style="width:20px"
                             v-if="scope.row.type === 4">
                        <img src="https://oss.mspbots.ai/app/mspbots_theme_icon/sync.png"
                             style="width:20px"
                             v-if="scope.row.type === 5">
                      </template>
                    </el-table-column>
                    <el-table-column min-width="120"
                                     :fit='true'
                                     label="Assignee">
                      <template slot-scope="scope">
                        <span>{{scope.row.realName}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column min-width="220"
                                     :fit='true'
                                     label="Date">
                      <template slot-scope="scope">
                        <span style="color:color:#c0c0c0;">{{scope.row.createTime | timeformat}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column min-width="470"
                                     :fit='true'>
                      <template slot-scope="scope">
                        <div style="position: relative;">
                          <div v-html="scope.row.summary"
                               style="width:600px"></div>
                          <div class="checklist_icon"
                               v-if="showClickIcon==true&&scope.row.id==rowid"
                               style="position: absolute;right:0;top:50%;transform:translate(0, -50%);">
                            <el-tooltip class="item"
                                        effect="dark"
                                        :content="$t('custom.component.gadget.check')"
                                        placement="top">
                              <el-button type="text"
                                         class="cuifont icon_checkmark_circle"
                                         :disabled="scope.row.readStatus !== 0"
                                         @click="openCheckDialog(scope.row)"
                                         style="color:#212529;"></el-button>
                            </el-tooltip>
                            <el-tooltip class="item"
                                        effect="dark"
                                        :content="$t('custom.component.gadget.ignore')"
                                        placement="top">
                              <el-button type="text"
                                         class="cuifont icon_block"
                                         :disabled="scope.row.readStatus !== 0"
                                         @click="ignoreHandler(scope.row)"
                                         style="margin-left:20px;color:#212529;"></el-button>
                            </el-tooltip>
                          </div>
                        </div>
                      </template>
                    </el-table-column>
                    <!-- <el-table-column v-for="item in selectFields" :key="item" min-width="200" :fit='true'
                                   :label="item">
                                   <template slot-scope="scope">
                                    <span>{{scope.row[item]}}</span>
                                  </template>
                  </el-table-column> -->
                  </el-table>
                  <el-pagination style="margin-top:10px;float: right;"
                                 @size-change="handleSizeChange"
                                 @current-change="handleCurrentChange"
                                 :current-page="currentPage"
                                 :page-sizes="[10, 20, 50, 100]"
                                 :page-size="pageSize"
                                 layout="total, sizes, prev, pager, next, jumper"
                                 :total="total">
                  </el-pagination>
                  <el-dialog top="30vh"
                             :append-to-body="true"
                             :visible.sync="checklistdDialogVisible"
                             width="470px">
                    <div slot="title"
                         class="header-title">
                      <img :src="$ossLink+'/app/mspbots_theme_icon/incomplete_settings.png'"
                           v-if="checkDialogData.type === 1"
                           style="width:20px;margin-right:10px">
                      <img :src="$ossLink+'/app/mspbots_theme_icon/integrations.png'"
                           v-if="checkDialogData.type === 2"
                           style="width:20px;margin-right:10px">
                      <img :src="$ossLink+'/app/mspbots_theme_icon/notification.png'"
                           v-if="checkDialogData.type === 3"
                           style="width:20px;margin-right:10px">
                      <img :src="$ossLink+'/app/mspbots_theme_icon/teams_command.png'"
                           v-if="checkDialogData.type === 4"
                           style="width:20px;margin-right:10px">
                      <img :src="$ossLink+'/app/mspbots_theme_icon/sync.png'"
                           v-if="checkDialogData.type === 5"
                           style="width:20px;margin-right:10px">
                      <span class="name"
                            v-if="checkDialogData.type === 1">{{$t('custom.component.gadget.incompleteSettings')}}</span>
                      <span class="name"
                            v-if="checkDialogData.type === 2">{{$t('custom.component.gadget.integrationStatus')}}</span>
                      <span class="name"
                            v-if="checkDialogData.type === 3">{{$t('custom.component.gadget.notification')}}</span>
                      <span class="name"
                            v-if="checkDialogData.type === 4">{{$t('custom.component.gadget.userDisable')}}</span>
                      <span class="name"
                            v-if="checkDialogData.type === 5">{{$t('custom.component.gadget.syncAuth')}}</span>
                    </div>
                    <span style="font-size: 18px;font-weight: 500;color: #404040;line-height: 25px;"
                          v-html="checkDialogData.summary"></span>
                    <div style="margin-top:20px">
                      <span style="font-size: 14px;line-height: 35px;"
                            class="cuifont icon_person"> {{$t('custom.component.gadget.creator')}}</span><span style="font-size:14px;line-height:30px;margin-left:18px;backgroundColor:#F0F0F0;padding:6px">{{checkDialogData.creatorName}}</span><br>
                      <span style="font-size: 14px;line-height: 35px;"
                            class="cuifont icon_people"> {{$t('custom.component.gadget.assignee')}}</span><span style="font-size:14px;line-height:30px;margin-left:8px;backgroundColor:#F0F0F0;padding:6px">{{checkDialogData.realName}}</span><br>
                      <span style="font-size: 14px;line-height: 35px;"
                            class="cuifont icon_flag"> {{$t('custom.component.gadget.priority')}}</span><span style="font-size:14px;line-height:30px;margin-left:20px;">
                        <el-badge is-dot
                                  class="item"
                                  style="padding:8px 5px 0 0"
                                  type="danger"
                                  v-if="checkDialogData.priority === 1"></el-badge><span v-if="checkDialogData.priority === 1">{{$t('custom.component.gadget.instant')}}</span>
                        <el-badge is-dot
                                  class="item"
                                  style="padding:8px 5px 0 0"
                                  type="warning"
                                  v-if="checkDialogData.priority === 2"></el-badge><span v-if="checkDialogData.priority === 2">{{$t('custom.component.gadget.urgent')}}</span>
                        <el-badge is-dot
                                  class="item"
                                  style="padding:8px 5px 0 0"
                                  type="success"
                                  v-if="checkDialogData.priority === 3"></el-badge><span v-if="checkDialogData.priority === 3">{{$t('custom.component.gadget.normal')}}</span>
                        <el-badge is-dot
                                  class="item"
                                  style="padding:8px 5px 0 0"
                                  type="info"
                                  v-if="checkDialogData.priority === 4"></el-badge><span v-if="checkDialogData.priority === 4">{{$t('custom.component.gadget.low')}}</span>
                      </span><br>
                    </div>
                    <span slot="footer"
                          class="dialog-footer">
                      <el-button size="mini"
                                 @click="ignoreHandler(checkDialogData)">{{$t('custom.component.gadget.ignore')}}</el-button>
                      <el-button size="mini"
                                 type="primary"
                                 @click="checkHandler(checkDialogData)">{{$t('custom.component.gadget.check')}}</el-button>
                    </span>
                  </el-dialog>
                </div>
                <div v-else
                     class="gadget-no-newdata">
                    <div class="widgets-no-data">
                    <div :style="{'fontSize':fontSizeStr1}">{{$t('custom.component.gadget.nodata')}}</div>
                    <!-- <div class="widgets-tip"> <a :href="widgetNoDataWiki"  :style="{'fontSize':fontSizeStr2}"
                         target="black">{{$t('custom.component.gadget.nodatatip')}}</a> </div> -->
                  </div>
                </div>
              </div>
            </div>
          </div>

        </el-card>
        <Lastupdatetime v-if="currentTime"
                        :currentTime="currentTime"
                        :linkedDatasetList="linkedDatasetList"
                        :errorStatus="errorStatus"
                        @updateQuery="query()"></Lastupdatetime>
      </DashboardInterceptConsumer>
    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           @queryModelPreview="queryModelPreview"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           @saveGadgetSetting='saveGadgetSetting' />
    <DrillThrough :gadgetId='id'
                  :pageId='pageId'
                  :slicer="slicer"
                  :queryId="queryId"
                  ref="drill-through"
                  :widgetName='widgetName' />
    <ExportOptionDialog :exportOptionDialogVisible="exportOptionDialogVisible"
                        @closeExportOptionDialog="closeExportOptionDialog"
                        @confirmExport="confirmExport"></ExportOptionDialog>
  </div>
</template>

<script>
import Vue from 'vue'
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import Lastupdatetime from '@/components/last-update-time/index.vue'
import linkFormat from './template/linkFormat'
import boolFormat from './template/boolFormat'
import progessFormat from './template/progessFormat'
import progessFullFormat from './template/progessfullFormat'
import DrillThroughLinkFormat from './template/DrillThroughLinkFormat'
import ticketLinkFormat from './template/ticketLinkFormat'
import timeEntryLinkFormat from './template/timeEntryLinkFormat'
import { DataTransmit } from './template/dataTransmit'
import dateFormat from './template/dateFormat'
import textFormat from './template/textFormat'
import { defaultGadgetSettingList } from '@/utils/data-json'
import { grids } from 'ejs'
import { GlobalTimeformat } from '@/utils/common'
import { v4 } from 'uuid'
import ExportOptionDialog from '@/components/export-option-dialog/dialog.vue'
import { debounce } from 'lodash'
export default {
  mixins: [mixinGadgetViewModule],
  components: { Lastupdatetime, model: () => import('@/components/gadget/query-model/query-model'), ExportOptionDialog },
  data () {
    return {
      floatNum: 0,
      maxColItem: 0,
      gadgetSetting: {},
      AggColumn: [],
      mixinViewModuleOptions: {
        pageId: this.pageId
      },
      isGridInit: false,
      dataList: [],
      loading: false,
      heightoffset: 60,
      currentTime: null,
      id: v4(),
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'checklistgadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'checklistgadget' }).gadgetSetting
        }
      },
      LinkFormat: function () {
        return { template: linkFormat }
      },
      BoolFormat: function () {
        return { template: boolFormat }
      },
      ProgessFormat: function () {
        return { template: progessFormat }
      },
      ProgessfullFormat: function () {
        return { template: progessFullFormat }
      },
      DrillThroughLinkFormat: function () {
        return { template: DrillThroughLinkFormat }
      },
      DateFormat: function () {
        return { template: dateFormat }
      },
      TicketLinkFormat: function () {
        return { template: ticketLinkFormat }
      },
      TimeEntryLinkFormat: function () {
        return { template: timeEntryLinkFormat }
      },
      TextFormat: function () {
        return { template: textFormat }
      },
      conditionFormat: [],
      footerTemp: function () {
        return {
          template: Vue.component('footerTemplate', {
            template: `<span>{{data.Custom}}</span>`,
            data () { return { data: {} } }
          })
        }
      },
      AverageTemp: function () {
        return {
          template: Vue.component('footerTemplate', {
            template: `<span>{{data.Custom}}</span>`,
            data () { return { data: {} } }
          })
        }
      },
      Min: function () {
        return {
          template: Vue.component('avgTemplate', {
            template: `<span>{{data.Min}}</span>`,
            data: function () { return { data: { data: {} } } }
          })
        }
      },
      Max: function () {
        return {
          template: Vue.component('avgTemplate', {
            template: `<span>{{data.Max}}</span>`,
            data: function () { return { data: { data: {} } } }
          })
        }
      },
      Count: function () {
        return {
          template: Vue.component('avgTemplate', {
            template: `<span>{{data.Count}}</span>`,
            data: function () { return { data: { data: {} } } }
          })
        }
      },
      toolbarItem: ['PdfExport', 'CsvExport', 'ColumnChooser'], // 'ExcelExport'
      wrapSettings: { wrapMode: 'Both' },
      queryId: '',
      queryDrillthrough: {},
      queryDrillthroughList: [],
      selectFields: [],
      widgetName: '',
      pageSize: 10,
      currentPage: 1,
      keyWords: '',
      showClickIcon: false,
      checklistdDialogVisible: false,
      checkDialogData: {
        assignee: null,
        component: null,
        create_time: null,
        creator: null,
        id: null,
        priority: null,
        readStatus: null,
        status: null,
        summary: null,
        tenant_code: null,
        type: null,
        update_by: null,
        update_time: null
      },
      filterVisible: false,
      assigneeOptions: JSON.parse(sessionStorage.getItem('assigneeOptions' + '-' + this.id)) || [],
      sortOptions: [{ label: 'Priority Descending', value: 'priority desc' }, { label: 'Priority Ascending', value: 'priority asc' }, { label: 'Earliest Creation Time', value: 'create_time asc' }, { label: 'Latest Creation Time', value: 'create_time desc' }, { label: 'Type Descending', value: 'type desc' }, { label: 'Type Ascending', value: 'type asc' }, { label: 'Assignee Z→A', value: 'realName asc' }, { label: 'Assignee A→Z', value: 'realName desc' }],
      filterform: JSON.parse(sessionStorage.getItem('filterform' + '-' + this.id)) || { status: null, priority: null, type: null, assignee: null, createTime: null, dateRange: null },
      statusOptions: [{ label: 'Uncheck', value: 0 }, { label: 'Ignore', value: 2 }, { label: 'Checked', value: 1 }],
      sortStatus: sessionStorage.getItem('sortStatus' + '-' + this.id) || 'create_time desc',
      filterStatus: '',
      dateOptions: [
        {
          value: 'Custom DateRange',
          label: 'Custom DateRange'
        },
        {
          value: '',
          label: 'Day',
          children: [
            { value: 'today', label: 'Today' },
            { value: 'yesterday', label: 'Yesterday' },
            { value: 'last 3 day', label: 'Last 3 days' },
            { value: 'last 7 day', label: 'Last 7 days' },
            { value: 'last 30 day', label: 'Last 30 days' }
          ]
        },
        {
          value: '',
          label: 'Week',
          children: [
            { value: 'This week', label: 'This week' },
            { value: 'last week', label: 'Last week' }
          ]
        },
        {
          value: '',
          label: 'Month',
          children: [
            { value: 'this month', label: 'This month' },
            { value: 'last month', label: 'Last month' }
          ]
        },
        {
          value: '',
          label: 'Quarter',
          children: [
            { value: 'this Quarter', label: 'This quarter' },
            { value: 'last Quarter', label: 'Last quarter' }
          ]
        },
        {
          value: '',
          label: 'Year',
          children: [
            { value: 'this year', label: 'This year' },
            { value: 'last year', label: 'Last year' }
          ]
        }
      ],
      startDatePickerVisable: false,
      linkedDatasetList: [],
      total: 0,
      keyWordsValue: ''
    }
  },

  filters: {
    assigneeFilter (val) {
      if (val && val.includes(' ')) {
        return val.split(' ')[0][0].toUpperCase() + val.split(' ')[1][0].toUpperCase()
      }
      return val
    },
    timeformat (time) {
      return GlobalTimeformat(time, 'HH:mm')
    }
  },
  created () {
    // this.query()
    Vue['_this'] = this
    DataTransmit.$on('needData', () => {
      DataTransmit.$emit('giveData', this)
    })
    this.subscribeMessage('runReport', () => {
      this.query(this.refreshCount > 0 ? 'auto' : false)
      this.refreshCount = this.refreshCount + 1
    })
    this.$store.state.isWidget = false
    this.gadgetHeight = this.pageFromType === 'report' ? (this.gadgetInfo.h * (this.rolHeight+10)-10) - 50 : (this.gadgetInfo.h * (this.rolHeight+12)-12) - 40
  },
  computed: {
    comDataList () {
      var _self = this
      // return Array.isArray(_self.dataList) ? _self.dataList : []
      var retdata = _self.dataList
      return retdata
    }
    // assigneeOptions () {
    //   return this._.uniqBy(this.comDataList, 'realName').filter(item => {
    //     return item.realName !== null
    //   })
    // }
  },
  watch: {
    editMode (val) {
      if (!val) {
        this.saveGadgetSetting()
      }
    }
    // 'filterform.dateRange': {
    //   handler: function (newValue, oldValue) {
    //     if (!newValue) {
    //       const that = this
    //       const end = new Date()
    //       const start = new Date()
    //       start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
    //       that.filterform.dateRange = []
    //       that.filterform.dateRange[0] = start
    //       that.filterform.dateRange[1] = end
    //     }
    //   },
    //   deep: true
    // }
  },
  methods: {
    inputFilter: debounce(function (val) {
      this.currentPage = 1
      this.keyWordsValue = val
      this.query()
    }, 1000),
    // datePickerChange (val) {
    //   this.$refs.dateCascader.dropDownVisible = true
    // },
    cascaderChange (val) {
      // if (val === 'Custom DateRange children') {
      //   this.$refs.dateCascader.dropDownVisible = true
      // }
      if (val === 'Custom DateRange') {
        const that = this
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
        that.filterform.dateRange = []
        that.filterform.dateRange[0] = start
        that.filterform.dateRange[1] = end
      }
    },
    showFilterForm () {
      this.filterform = JSON.parse(sessionStorage.getItem('filterform' + '-' + this.id)) || { status: null, priority: null, type: null, assignee: null, createTime: null, dateRange: null }
    },
    filterformReset () {
      this.filterform = { status: null, priority: null, type: null, assignee: null, createTime: null, dateRange: null }
    },
    filterformApply (val) {
      sessionStorage.setItem('filterform' + '-' + this.id, JSON.stringify(this.filterform))
      this.$refs['filterPopover'].doClose()
      this.currentPage = 1
      this.query()
    },
    filterCommand (val) {
      this.filterStatus = val
    },
    sortCommand (val) {
      this.sortStatus = val
      sessionStorage.setItem('sortStatus' + '-' + this.id, this.sortStatus)
      this.currentPage = 1
      this.query()
    },
    rowStyle ({ row, rowIndex }) {
      let stylejson = {}
      if (row.readStatus === 2) {
        stylejson.backgroundColor = '#F5F7FA'
      } else if (row.readStatus === 1) {
        stylejson.color = '#C0C0C0'
      }
      return stylejson
    },
    openCheckDialog (row) {
      this.checkDialogData = row
      this.checklistdDialogVisible = true
    },
    ignoreHandler (row) {
      this.$confirm('Are you sure to ignore?', 'Warning', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        this.checklistdDialogVisible = false
        const params = row
        params.readStatus = 2
        this.loading = true
        this.$interface.reports.putChecklistApi(params).then(({ data: res }) => {
          if (res.code !== 0) {
            this.loading = false
            return this.$message.error(res.msg)
          }
          this.$message({
            type: 'success',
            message: 'Successfully ignore!'
          })
          this.query()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'ignore canceled'
        })
      })
    },
    checkHandler (row) {
      this.checklistdDialogVisible = false
      const params = row
      params.readStatus = 1
      this.loading = true
      this.$interface.reports.putChecklistApi(params).then(({ data: res }) => {
        if (res.code !== 0) {
          this.loading = false
          return this.$message.error(res.msg)
        }
        this.$message({
          type: 'success',
          message: 'Successfully checked!'
        })
        this.query()
      })
    },
    ncrFormat (row) {
      this.showClickIcon = true
      this.rowid = row.id
      this.rowData = row
    },
    handleSizeChange (val) {
      this.pageSize = val
      this.query()
    },
    handleCurrentChange (val) {
      this.currentPage = val
      this.query()
    },
    sortComparer: function (reference, comparer) {
      if (reference === 0 && this.isNull(comparer)) {
        return 1
      }
      if (reference < comparer) {
        return -1
      }
      if (reference > comparer) {
        return 1
      }
      return 0
    },
    isNull (value) {
      if (!value && typeof value !== 'undefined' && value !== 0) {
        return true
      } else {
        return false
      }
    },
    customSumFn: function (data, col) {
      let countLength = 0
      let floatNum = 0
      let num = 0
      for (let index = 0; index < this.dataList.length; index++) {
        let item = this.dataList[index]
        let data = grids.getObject(col.field, item)
        if (!data) continue
        let numData = Number(data)
        countLength += numData
      }
      if (!Number.isInteger(countLength)) { num = countLength.toString().split('.')[1].length }
      if (num < 3) floatNum = num
      else floatNum = 2
      return this.toDecimal(countLength, floatNum)
    },
    toDecimal (x, m) {
      var val = Number(x)
      if (!isNaN(parseFloat(val))) {
        val = val.toFixed(m)
      }
      return val
    },
    customAggregateFn: function (data, col) {
      let count = grids.getObject('count', data)
      let Aggregate = 0
      for (let index = 0; index < this.dataList.length; index++) {
        let item = this.dataList[index]
        let data = grids.getObject(col.field, item)
        if (!data) continue
        let numData = Number(data)
        Aggregate += numData
      }
      let point = 2
      for (let index = 0; index < this.gadgetSetting.report.columns.length; index++) {
        let item = this.gadgetSetting.report.columns[index]
        if (col.field === item.field) {
          point = item.decimalPoint
          break
        }
      }
      // return Aggregate / count
      return this.fomatFloat(Aggregate / count, point)
    },
    fomatFloat (src, pos) {
      return Math.round(src * Math.pow(10, pos)) / Math.pow(10, pos)
    },
    returntempate (type) {
      if (type === 'Sum') {
        return this.Sum
      } else if (type === 'Average') {
        return this.Average
      } else if (type === 'Min') {
        return this.Min
      } else if (type === 'Max') {
        return this.Max
      } else if (type === 'Count') {
        return this.Count
      }
    },
    extractColumn () {
      this.maxColItem = 0
      let parentArr = []
      for (let i = 0; i < 5; i++) {
        let itemArr = []
        for (let index = 0; index < this.gadgetSetting.report.columns.length; index++) {
          let item = this.gadgetSetting.report.columns[index]
          if (item.type === 'number' && item.aggregates.length > 0) {
            if (this.maxColItem < item.aggregates.length) this.maxColItem = item.aggregates.length
            if (item.aggregates[i]) {
              itemArr.push({
                value: item.aggregates[i],
                field: item.field
              })
            }
          }
        }
        if (itemArr.length > 0) parentArr.push(itemArr)
      }
      this.AggColumn = parentArr
    },
    recordClick (args) {
      if (!args.rowData[args.column.foreignKeyField]) {
        return
      }
      var tempAlias = ''
      var tempData = ''
      var tempList = []
      var alias = ''
      var pointx = ''
      // if (this.queryDrillthroughList.length > 1) {
      //   var list = this.selectFields.filter(item => item.queryId === (this.selectFields.find(item => item.alias === args.column.foreignKeyField).queryId))
      //   var field = (list.find(i => i.dataType === 'dimension')).field
      //   tempList.push({
      //     item: '"' + (field || '') + '"' + "='" + (args.rowData['dimesion1'] ? args.rowData['dimesion1'] : '') + "'"
      //   })
      // } else {
      if (this.queryDrillthroughList && this.queryDrillthroughList.length > 0) {
        for (let index = 0; index < this.queryDrillthroughList.length; index++) {
          const element = this.queryDrillthroughList[index]
          tempList.push({
            item: '"' + (element.field ? element.field : '') + '"' + "='" + (args.rowData[element.alias] ? args.rowData[element.alias] : '') + "'"
          })
        }
      } else {
        if (this.queryDrillthrough && this.queryDrillthrough.alias) {
          tempAlias = args.rowData[this.queryDrillthrough.alias]
          if (!tempAlias && tempAlias !== false && tempAlias !== 0) {
            alias = 'dimesion1'
          } else {
            alias = this.queryDrillthrough.alias
          }
          pointx = args.rowData[alias]
          if (!pointx && pointx !== false && pointx !== 0) {
            pointx = ' is null'
          } else {
            pointx = "= '" + pointx + "'"
          }
          tempData = '"' + (this.queryDrillthrough.field ? this.queryDrillthrough.field : '') + '"' + pointx
        }
      }
      // }
      if (tempList && tempList.length > 0) {
        for (let i = 0; i < tempList.length; i++) {
          if (i === tempList.length - 1) {
            tempData += tempList[i].item
          } else {
            tempData += tempList[i].item + ' and '
          }
        }
      }
      this.queryId = this.selectFields.find(item => item.alias === args.column.foreignKeyField) ? this.selectFields.find(item => item.alias === args.column.foreignKeyField).queryId : ''
      if (this.queryId) {
        let data = ''
        data = tempData
        this.findOriginData(data)
      }
    },
    customiseCell (args) {
      var arr = this.conditionFormat
      var column = args.column.field
      var res = arr.filter(item => {
        if (item.dataForm.filters.rules.length !== 0) {
          return item.dataForm.filters.rules[0].key === column
        }
      })
      if (args.data) {
        res.reverse().forEach(it => {
          if (it) {
            if (args.data[it.dataForm.filters.rules[0].key] === null) return
            // eslint-disable-next-line
            var val = args.data[it.dataForm.filters.rules[0].key].toString().replace(/[\$\,]/g, '')
            if (val.includes('%')) {
              // eslint-disable-next-line
              val = Number(val.replace(/%/g, '')) / 100
            } else if (val.indexOf('k') > -1) {
              // eslint-disable-next-line
              val = Number(val.replace(/k/g, '')) * 1000
            }
            if (it.dataForm.filters.rules[0].opt === '=') {
              it.dataForm.filters.rules[0].opt = '=='
            }
            // eslint-disable-next-line
            if (it && eval(Number(val) + it.dataForm.filters.rules[0].opt + Number(it.dataForm.filters.rules[0].value))) {
              args.cell.style.color = it.textColor
              args.cell.style.backgroundColor = it.backgroundColor
            }
          }
        })
      }
    },
    dataBound (args) {
      if (!this.isGridInit) {
        this.isGridInit = true
        this.applyGadgetSetting()
      }
    },
    load (item) {
      this.grid = this.$refs.datagrid
      // this.gadgetHeight = this.gadgetInfo.h * 20 - 15
    },
    applyGadgetSetting () {
      let columnsList = []
      let isAutofit = false
      // process link column
      for (let index = 0; index < this.gadgetSetting.report.columns.length; index++) {
        const element = this.gadgetSetting.report.columns[index]
        // add template and drillThrough
        columnsList.push(element.field)
        if (this.gadgetSetting.report.columns[0] && !this.gadgetSetting.report.columns[0].width) {
          isAutofit = true
        }

        if (element.templateName && element.templateName === 'linkFormat') {
          this.gadgetSetting.report.columns[index].template = this.LinkFormat
        } else if (element.templateName && element.templateName === 'boolFormat') {
          this.gadgetSetting.report.columns[index].template = this.BoolFormat
        } else if (element.templateName && element.templateName === 'progessFormat') {
          this.gadgetSetting.report.columns[index].template = this.ProgessFormat
        } else if (element.templateName && element.templateName === 'dateFormat') {
          this.gadgetSetting.report.columns[index].template = this.DateFormat
        } else if (element.templateName && element.templateName === 'progessFullFormat') {
          this.gadgetSetting.report.columns[index].template = this.ProgessfullFormat
        } else if (element.templateName && element.templateName === 'ticketLinkFormat') {
          this.gadgetSetting.report.columns[index].template = this.TicketLinkFormat
        } else if (element.templateName && element.templateName === 'timeEntryLinkFormat') {
          this.gadgetSetting.report.columns[index].template = this.TimeEntryLinkFormat
        } else if (element.templateName && element.templateName === 'textFormat') {
          this.gadgetSetting.report.columns[index].template = this.TextFormat
        }
        try {
          if (element.drillThrough && element.drillThrough.status) {
            this.gadgetSetting.report.columns[index].template = this.DrillThroughLinkFormat
          }
        } catch (e) {
        }
        // datetime format bugfix
        if (this.gadgetSetting.report.columns[index].type === 'datetime') {
          this.gadgetSetting.report.columns[index].type = 'text'
        }
        if (this.gadgetSetting.report.columns[index].type === 'date') {
          this.gadgetSetting.report.columns[index].type = 'text'
        }
      }
      if (isAutofit) {
        columnsList = Object.keys(this.dataList[0])
        this.grid.ej2Instances.autoFitColumns(columnsList)
      }
      this.grid.ej2Instances.setProperties(this.gadgetSetting.report)
    },
    findColumnIndex (arr) {
      for (let index = 0; index < arr.length; index++) {
        const element = arr[index]
        if (element.field === 'Name') {
          return index
        }
      }
      return -1
    },
    saveGadgetSetting () {
      var _self = this
      if (_self.grid) {
        var report = JSON.parse(_self.grid.ej2Instances.getPersistData())
        this._.merge(_self.gadgetSetting.report, report)
        delete _self.gadgetSetting.report
        // grid table , save obj  from json obj
        // const params = {
        //   gadgetSetting: {
        //     report: report
        //   },
        //   gadgetId: this.id
        // }
        // this.$interface.reports.putReportsSettingApi(params).then(({ data: res }) => {
        //   if (res.code !== 0) {
        //     return _self.$message.error(res.msg)
        //   }
        // })
      }
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query(true)
    },
    queryModelPreview () {
      this.query(true)
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = this.pageFromType === 'report' ? (newH * (this.rolHeight+10)-10) - 50 : (newH * (this.rolHeight+12)-12) - 40
      this.gadgetWidth = newWPx
    },
    toolbarClick (args) {
      switch (args.item.text) {
        case 'PDF Export':
          if (this.gadgetSetting.report.showExportOption) {
            this.exportOptionDialogVisible = true
          } else {
            this.$refs.datagrid.pdfExport()
          }
          break
        case 'Excel Export':
          (this.$refs['datagrid']).excelExport()
          break
        case 'CSV Export':
          (this.$refs['datagrid']).csvExport()
          break
      }
    },
    query (e) {
      // this.dataList = []
      try {
        this.gadgetSetting.report.columns = []
      } catch (error) { }
      if (e !== 'auto') {
        this.loading = true
        this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      }
      var _self = this

      var params = {
        orderparams: this.sortStatus,
        priority: this.filterform.priority,
        readStatus: this.filterform.status,
        type: this.filterform.type,
        assignee: this.filterform.assignee,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        gadgetId: this.id,
        page: {
          current: this.currentPage,
          size: this.pageSize
        }
      }
      if (this.keyWordsValue && this.keyWordsValue.trim()) {
        params.summary = this.keyWordsValue
      }
      if (this.filterform.createTime === 'Custom DateRange') {
        params.startTime = this.filterform.dateRange[0]
        params.endTime = this.filterform.dateRange[1]
      } else {
        params.sqlparams = this.filterform.createTime
      }
      this.$interface.clientDesired.getCheckListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return
          }
          if (res.data && res.data.records && res.data.records.length > 0) {
            this.verifyHasData(res)
            for (var key in res.data[0]) {
              if (key !== 'priority' && key !== 'type' && key !== 'summary' && key !== 'createTime') {
                _self.selectFields.push(key)
              }
            }
            if (!sessionStorage.getItem('filterform' + '-' + this.id)) {
              this.assigneeOptions = this._.uniqBy(res.data, 'realName').filter(item => {
                return item.realName !== null
              })
              sessionStorage.setItem('assigneeOptions' + '-' + this.id, JSON.stringify(this.assigneeOptions))
            }
            _self.linkedDatasetList = res.datasetSync
            _self.dataList = res.data.records
            _self.total = +res.data.total
          }
        })
        .catch((error) => {
          this.isHasData = false
          this.loading = false
          if (error.response && error.response.status === 504) {
            this.errorStatus = '504'
            this.gadgetMessageBus.$emit(this.pageId + 'stopautorefresh')
          }
        }).finally(() => {
          this.currentTime = new Date()
          this.autoRefreshQuery(e)
          this.updateGadgetLoadingStatus(!this.loading)
        })
    },
    destroyed () {
      delete Vue['_this']
    },
    remove () {
      this.close()
      if (this.drop.parentNode) {
        this.drop.parentNode.removeChild(this.drop)
      }
    },
    closeExportOptionDialog () {
      this.exportOptionDialogVisible = false
    },
    confirmExport (options) {
      this.$refs.datagrid.pdfExport(options)
      this.exportOptionDialogVisible = false
    }
  },
  destroyed () {
    DataTransmit.$off('needData')
  }
}
</script>
<style lang="scss" scoped>
.content-wrapper {

  .gadget-no-newdata {
  
    .widgets-no-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      .widgets-tip {
        margin-top: 5px;
      }
    }
  }
}
</style>
<style scoped>
.grid_gadget_tempalte ::v-deep .e-grid .e-summarycell {
  font-size: 13px;
  background-color: #f6f6f6;
  border-color: #e0e0e0;
  color: rgba(0, 0, 0, 0.54);
  font-weight: normal;
}
.el-card ::v-deep .el-card__body {
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}
.el-table__body tbody {
  overflow: auto !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardHeader > span {
  display: inline-block;
  width: calc(100% - 30px);
}

.cardTitle {
  font-size: 16px;
  color: #000;
  font-weight: 700;
  display: inline-block;
  max-width: calc(100% - 30px);
  position: relative;
  top: 2px;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}

.toolbar {
  display: flex;
  justify-content: flex-end;
  cursor: pointer;
}

.header {
  display: flex;
  height: 32px;
  justify-content: space-around;
  text-align: center;
  background: no-repeat;
  background-size: cover;
}

.e-grid ::v-deep .e-filter-popup {
  max-height: 300px !important;
  overflow-y: auto;
}

.e-grid ::v-deep .e-checkboxlist {
  height: auto !important;
  overflow-y: visible !important;
}
.checklist_icon span:hover {
  cursor: pointer;
}
::v-deep .el-table tbody tr:hover > td {
  background-color: #e6ebf3;
}
.selected {
  color: #17b3a3;
}
::v-deep .el-form-item__label {
  padding: 0 !important;
}
::v-deep .el-form-item {
  margin-bottom: 0 !important;
}
.filterformReset:hover {
  cursor: pointer;
}
::v-deep .el-badge__content.is-dot {
  width: 10px !important;
  height: 10px !important;
}
::v-deep .el-dialog__body {
  padding-top: 0 !important;
}
</style>
